package com.neihe.config;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;

        // 允许所有域名访问
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许所有请求头
        response.setHeader("Access-Control-Allow-Headers", "*");
        // 允许所有方法
        response.setHeader("Access-Control-Allow-Methods", "*");
        // 允许暴露所有响应头
        response.setHeader("Access-Control-Expose-Headers", "*");
        // 允许携带认证信息(可选)
        // response.setHeader("Access-Control-Allow-Credentials", "true");

        // 预检请求的有效期,单位:秒
        response.setHeader("Access-Control-Max-Age", "3600");

        // 对于预检请求，直接返回
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        chain.doFilter(req, res);
    }

}